//
//  KDCalendarPicker.m
//  LaiKeDaoClient
//
//  Created by dongkedi的iMac on 15/11/3.
//  Copyright © 2015年 LKD. All rights reserved.
//

#import "KDCalendarPicker.h"
#import "SZCalendarCell.h"

#define titleHeigth 54
#define collectionHeigth 230
#define collectionBackColor @"#cccccc"

NSString *const SZCalendarCellIdentifier = @"cell";

@implementation KDCalendarPicker
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.type = 0;
        [self createUI];
    }
    return self;
}

- (void)createUI
{
    UIImageView *monthImageView = [[UIImageView alloc] initWithFrame:(CGRect){kScreenWidth/2 - 29/2,14,29,29}];
    [monthImageView setImage:[UIImage imageNamed:@"circle_month@2X.png"]];
    [self addSubview:monthImageView];
    
    self.monthLabel = [[UILabel alloc] initWithFrame:monthImageView.bounds];
    [_monthLabel setTextAlignment:NSTextAlignmentCenter];
    [_monthLabel setFont:[UIFont systemFontOfSize:12]];
    [monthImageView addSubview:_monthLabel];
    
    self.preMonthLabel = [[UILabel alloc] initWithFrame:(CGRect){193/2,Y(monthImageView),WIDTH(_monthLabel),HEIGHT(_monthLabel)}];
    [_preMonthLabel setTextAlignment:NSTextAlignmentCenter];
    [_preMonthLabel setFont:[UIFont systemFontOfSize:12]];
    [self addSubview:_preMonthLabel];
    
    self.nextMonthLabel = [[UILabel alloc] initWithFrame:(CGRect){X(monthImageView)+WIDTH(monthImageView)+14+6,Y(monthImageView),WIDTH(_monthLabel),HEIGHT(_monthLabel)}];
    [_nextMonthLabel setTextAlignment:NSTextAlignmentCenter];
    [_nextMonthLabel setFont:[UIFont systemFontOfSize:12]];
    [self addSubview:_nextMonthLabel];
    
    UIImageView *perMonthImageView = [[UIImageView alloc] initWithFrame:(CGRect){X(_preMonthLabel)+WIDTH(_preMonthLabel)+6,24,13/2,21/2}];
    [perMonthImageView setImage:[UIImage imageNamed:@"btn_pre@2X.png"]];
    [self addSubview:perMonthImageView];
    
    UIImageView *nextMonthImageView = [[UIImageView alloc] initWithFrame:(CGRect){X(monthImageView)+WIDTH(monthImageView)+10,24,13/2,21/2}];
    [nextMonthImageView setImage:[UIImage imageNamed:@"btn_next2@2x.png"]];
    [self addSubview:nextMonthImageView];
    
    self.previousButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.previousButton setFrame:(CGRect){193/2,14,50,30}];
    [self.previousButton setBackgroundColor:[UIColor clearColor]];
    [self addSubview:self.previousButton];
    [self.previousButton addTarget:self action:@selector(previouseAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.nextButton setFrame:(CGRect){180,14,50,30}];
    [self.nextButton setBackgroundColor:[UIColor clearColor]];
    [self addSubview:self.nextButton];
    [self.nextButton addTarget:self action:@selector(nexAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.collectionView = [[UICollectionView alloc] initWithFrame:(CGRect){32,titleHeigth,WIDTH(self)-64,collectionHeigth} collectionViewLayout:flowLayout];
    [_collectionView setBackgroundColor:[UIColor colorWithHexString:collectionBackColor]];
    [_collectionView registerClass:[SZCalendarCell class] forCellWithReuseIdentifier:SZCalendarCellIdentifier];
    _weekDayArray = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self addSubview:_collectionView];
    
    [self addSwipe];
}

- (void)setDate:(NSDate *)date
{
    _date = date;
    [_monthLabel setText:[NSString stringWithFormat:@"%.2ld月",(long)[self month:date]]];
    [_preMonthLabel setText:[NSString stringWithFormat:@"%.2ld月",(((long)[self month:date])-1 == 0 ? 12 : (long)[self month:date]-1)]];
    [_nextMonthLabel setText:[NSString stringWithFormat:@"%.2ld月",(((long)[self month:date])+1 == 13 ? 1 : (long)[self month:date]+1)]];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kRefeshCalendarBackColor object:nil];
    if ([self.pickerDelegate respondsToSelector:@selector(chooseCurrentDateMonth:Year:)]) {
        [self.pickerDelegate chooseCurrentDateMonth:[self month:date] Year:[self year:date]];
    }

    [_collectionView reloadData];
}

#pragma mark - date

- (NSInteger)day:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components day];
}


- (NSInteger)month:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components month];
}

- (NSInteger)year:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components year];
}


- (NSInteger)firstWeekdayInThisMonth:(NSDate *)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    [calendar setFirstWeekday:1];//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
    NSDateComponents *comp = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    [comp setDay:1];
    NSDate *firstDayOfMonthDate = [calendar dateFromComponents:comp];
    
    NSUInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDayOfMonthDate];
    return firstWeekday - 1;
}

- (NSInteger)totaldaysInThisMonth:(NSDate *)date{
    NSRange totaldaysInMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return totaldaysInMonth.length;
}

- (NSInteger)totaldaysInMonth:(NSDate *)date{
    NSRange daysInLastMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return daysInLastMonth.length;
}

- (NSDate *)lastMonth:(NSDate *)date{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.month = -1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}

- (NSDate*)nextMonth:(NSDate *)date{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.month = +1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}

#pragma -mark collectionView delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return _weekDayArray.count;
    } else {
        return 42;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(WIDTH(collectionView)/7 -0.1, collectionHeigth / 7 +0.8);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SZCalendarCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:SZCalendarCellIdentifier forIndexPath:indexPath];
    
    if (self.type == 0) {
        //
        if (indexPath.section == 0) {
            [cell reloadCell:indexPath haveStar:YES];
            [cell.dateLabel setText:_weekDayArray[indexPath.row]];
            [cell.dateLabel setTextColor:[UIColor blackColor]];
        } else {
            NSInteger daysInThisMonth = [self totaldaysInMonth:_date];
            NSInteger firstWeekday = [self firstWeekdayInThisMonth:_date];
            
            NSInteger day = 0;
            NSInteger i = indexPath.row;
            
            
            
            if (i < firstWeekday) {
                [cell.dateLabel setText:@""];
                [cell reloadCell:indexPath haveStar:YES];
            }else if (i > firstWeekday + daysInThisMonth - 1){
                [cell.dateLabel setText:@""];
                [cell reloadCell:indexPath haveStar:YES];
            }else{
                day = i - firstWeekday + 1;
                [cell.dateLabel setText:[NSString stringWithFormat:@"%li",(long)day]];
                [cell.dateLabel setTextColor:[UIColor blackColor]];
                [cell reloadCell:indexPath haveStar:NO];
                if (self.dataArr && self.dataArr.count > 0) {
                    cell.starImageView.hidden = YES;
                    for (NSString *str1 in self.dataArr) {
                        if ([str1 isEqualToString:cell.dateLabel.text]) {
                            cell.starImageView.hidden = NO;
                        }
                    }
                }
                //this month
                if ([_today isEqualToDate:_date]) {
                    if (day == [self day:_date]) {
                        [cell.dateLabel setTextColor:[UIColor colorWithHexString:@"#4898eb"]];
                    } else if (day > [self day:_date]) {
                        [cell.dateLabel setTextColor:[UIColor blackColor]];
                    }
                } else if ([_today compare:_date] == NSOrderedAscending) {
                    [cell.dateLabel setTextColor:[UIColor blackColor]];
                }
            }
        }

    }else if (self.type == 1){
        if (indexPath.section == 0) {
            [cell reloadCell:0 haveStar:YES];
            [cell.dateLabel setText:_weekDayArray[indexPath.row]];
            [cell.dateLabel setTextColor:[UIColor blackColor]];
        } else {
            NSInteger daysInThisMonth = [self totaldaysInMonth:_date];
            NSInteger firstWeekday = [self firstWeekdayInThisMonth:_date];
            
            NSInteger day = 0;
            NSInteger i = indexPath.row;
            
            
            
            if (i < firstWeekday) {
                [cell.dateLabel setText:@""];
                [cell reloadCell:0 haveStar:YES];
            }else if (i > firstWeekday + daysInThisMonth - 1){
                [cell.dateLabel setText:@""];
                [cell reloadCell:0 haveStar:YES];
            }else{
                day = i - firstWeekday + 1;
                [cell.dateLabel setText:[NSString stringWithFormat:@"%li",(long)day]];
                [cell.dateLabel setTextColor:[UIColor blackColor]];
                [cell reloadCell:0 haveStar:YES];
                //this month
                if ([_today isEqualToDate:_date]) {
                    if (day == [self day:_date]) {
                        [cell.dateLabel setTextColor:[UIColor colorWithHexString:@"#4898eb"]];
                    } else if (day > [self day:_date]) {
                        [cell.dateLabel setTextColor:[UIColor blackColor]];
                    }
                } else if ([_today compare:_date] == NSOrderedAscending) {
                    [cell.dateLabel setTextColor:[UIColor blackColor]];
                }
            }
        }
    }
    return cell;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        NSInteger daysInThisMonth = [self totaldaysInMonth:_date];
        NSInteger firstWeekday = [self firstWeekdayInThisMonth:_date];
        
        NSInteger day = 0;
        NSInteger i = indexPath.row;
        
        if (i >= firstWeekday && i <= firstWeekday + daysInThisMonth - 1) {
            day = i - firstWeekday + 1;
            if (_type == 0) {
                if (self.dataArr && self.dataArr.count > 0) {
                    for (NSString *str1 in self.dataArr) {
                        if ([str1 integerValue] == i) {
                            return YES;
                        }
                    }
                }
            }else if (_type == 1){
                return YES;
            }
            
            //this month
//            if ([_today isEqualToDate:_date]) {
//                if (day <= [self day:_date]) {
//                    return YES;
//                }
//            } else if ([_today compare:_date] == NSOrderedDescending) {
//                return YES;
//            }
//            return YES;
        }
    }
    return NO;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDateComponents *comp = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:self.date];
    NSInteger firstWeekday = [self firstWeekdayInThisMonth:_date];
    
    NSInteger day = 0;
    NSInteger i = indexPath.row;
    day = i - firstWeekday + 1;
    
    if ([self.pickerDelegate respondsToSelector:@selector(pickerClickDay:Month:Year:)]) {
        [self.pickerDelegate pickerClickDay:day Month:[comp month] Year:[comp year]];
    }
    
    SZCalendarCell *cell = (SZCalendarCell *)[collectionView cellForItemAtIndexPath:indexPath];
    [[NSNotificationCenter defaultCenter] postNotificationName:kRefeshCalendarBackColor object:cell];
}

- (IBAction)previouseAction:(UIButton *)sender
{
    [UIView transitionWithView:self.collectionView duration:0.5 options:UIViewAnimationOptionTransitionCurlDown animations:^(void) {
        self.date = [self lastMonth:self.date];
    } completion:nil];
}

- (IBAction)nexAction:(UIButton *)sender
{
    [UIView transitionWithView:self.collectionView duration:0.5 options:UIViewAnimationOptionTransitionCurlUp animations:^(void) {
        self.date = [self nextMonth:self.date];
    } completion:nil];
}

+ (instancetype)showOnView:(UIView *)view
{
    KDCalendarPicker *calendarPicker = [[KDCalendarPicker alloc] initWithFrame:view.bounds];
    
    [view addSubview:calendarPicker];
    return calendarPicker;
}

- (void)reloadCollectionViewData:(NSArray *)dataArr
{
    self.dataArr = dataArr;
    [self.collectionView reloadData];
}

- (void)addSwipe
{
//    UISwipeGestureRecognizer *swipLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(nexAction:)];
//    swipLeft.direction = UISwipeGestureRecognizerDirectionLeft;
//    [self addGestureRecognizer:swipLeft];
//    
//    UISwipeGestureRecognizer *swipRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(previouseAction:)];
//    swipRight.direction = UISwipeGestureRecognizerDirectionRight;
//    [self addGestureRecognizer:swipRight];
}
@end
